

public class Map {

	public int gridSize;
	public int xGrids, yGrids;

	public Obstacle verticalObstacles[][];
	public Obstacle horizontalObstacles[][];
	public Grid grids[][];

	public Map(int sizeX, int sizeY){
		
		gridSize = Constants.GRID_SIZE;
		
		xGrids = sizeX/gridSize;
		yGrids = sizeY/gridSize;

		grids = new Grid[xGrids][yGrids];
		verticalObstacles = new Obstacle[xGrids-1][yGrids];
		horizontalObstacles = new Obstacle[xGrids][yGrids-1];
		
		for(int i=0; i<xGrids-1; i++)
			for(int j=0; j<yGrids; j++)
				verticalObstacles[i][j] = new Obstacle();
		
		for(int i=0; i<xGrids; i++)
			for(int j=0; j<yGrids-1; j++)
				horizontalObstacles[i][j] = new Obstacle();
		
		for(int i=0; i<xGrids; i++)
			for(int j=0; j<yGrids; j++)
				grids[i][j] = new Grid();
	}

	public void setObstacle(int x, int y, boolean exists, boolean vertical){
		if(x < 0 || y < 0)
			return;
		
		if(vertical){
			if(x >= xGrids - 1 || y >= yGrids)
				return;
			//		if(!verticalObstacles[x][y].known){
			verticalObstacles[x][y].known = true;
			verticalObstacles[x][y].exists = exists;
			checkClosedGrid(x, y);
			checkClosedGrid(x + 1, y);
			//		}
		}
		else{
			if(x >= xGrids || y >= yGrids - 1)
				return;
			//		if(!horizontalObstacles[x][y].known){
			horizontalObstacles[x][y].known = true;
			horizontalObstacles[x][y].exists = exists;
			checkClosedGrid(x, y);
			checkClosedGrid(x, y + 1);
			//		}
		}


	}
	
	public void adjustSeenValues(){
		for(int i = 0; i < xGrids; i++)
			for(int j = 0; j < yGrids; j++)
				grids[i][j].seen = (int) Math.signum(grids[i][j].seen);
	}
	
	public void checkClosedGrid(int x, int y){
		boolean open = false;
		for(int i = 0; i < 4; i++){
			open |= isForwardAvailable(x, y, i);
		}
		try{
			if(!open)
				grids[x][y].closed = true;
		}
		catch(Exception e){}
	}
	
	public boolean isForwardAvailable(int x, int y, int dir) {
		try {
			if(dir == Constants.RIGHT)
				return !verticalObstacles[x][y].exists;
			
			else if(dir == Constants.DOWN)
				return !horizontalObstacles[x][y].exists;
			
			else if(dir == Constants.LEFT)
				return !verticalObstacles[x - 1][y].exists;
			
			else if(dir == Constants.UP)
				return !horizontalObstacles[x][y - 1].exists;
		} catch(Exception e) {
			return false;
		}
		return false;
	}
	
	public void nearbyObstacles(boolean[] obstacles, int x, int y){
		for(int i = 0; i < 4; i++){
			obstacles[i] = !isForwardAvailable(x, y, i);
		}
	}

}
